//
//  BHImagePickManager.swift
//  DoctorEPlus
//
//  Created by 王林波 on 2020/12/25.
//

import UIKit
import Photos

enum ImagePickType {
    case camera, photoAlbum
}

class BHImagePickManager: NSObject {
    // 初始化方法
    static let shareInstance = BHImagePickManager()
    // 当前操作的视图
    var currentVC: UIViewController?
    var type: ImagePickType = .camera
    // 是否可编辑
    var allowsEditing: Bool = false
    // 拍照的回调
    var takeImageCompleteHandler: ((UIImage?) -> Void)?
    // 选择照片的回调
    var choseImageCompleteHandler: ((UIImage?,PHAsset?) -> Void)?

    fileprivate var cameraPicker: UIImagePickerController!

    
    // 调相机
    func takeCamera(block: @escaping (UIImage?) -> Void) {
        self.takeImageCompleteHandler = block
        self.type = .camera
        if self.isCameraAvailable() == true {
            DispatchQueue.main.async {
                self.cameraPicker = UIImagePickerController()
                self.cameraPicker.allowsEditing = self.allowsEditing
                self.cameraPicker.sourceType = .camera
                self.cameraPicker.cameraCaptureMode = .photo
                self.cameraPicker.modalPresentationStyle = .fullScreen
                if self.currentVC == nil {
                    BHBaseViewController.currentViewController?.present(self.cameraPicker, animated: true) {
                        self.cameraPicker.delegate = self
                    }
                }else {
                    self.currentVC?.present(self.cameraPicker, animated: true, completion: nil)
                }
                
            }
        }else {
            block(nil)
        }
    }
    
    func selectPhoto(block: @escaping (UIImage?,PHAsset?) -> Void)  {
        self.type = .photoAlbum
        self.choseImageCompleteHandler = block
        
        if self.isAlbumAvailable() == true {
            DispatchQueue.main.async {
                self.cameraPicker = UIImagePickerController()
                self.cameraPicker.allowsEditing = self.allowsEditing
                self.cameraPicker.sourceType = .photoLibrary
                self.cameraPicker.delegate = self
                self.cameraPicker.modalPresentationStyle = .fullScreen
                if self.currentVC == nil {
                    BHBaseViewController.currentViewController?.present(self.cameraPicker, animated: true) {
                    }
                }else {
                    self.currentVC?.present(self.cameraPicker, animated: true, completion: nil)
                }
            }
        }else {
            block(nil,nil)
        }
    }
    
    
    // 检查相机是否可用
    private func isCameraAvailable() -> Bool{
        return UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)
    }
    
    // 检查相册是否可用
    private func isAlbumAvailable() -> Bool{
        return UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary)
    }
    
}

extension BHImagePickManager: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
        if self.type == .camera {
            self.takeImageCompleteHandler?(nil)
        }else {
            self.choseImageCompleteHandler?(nil,nil)
        }
    }
    
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if self.type == .camera {
            let image = info[(UIImagePickerController.InfoKey.originalImage)] as! UIImage?

            if let image = image?.fixOrientation() {
                self.takeImageCompleteHandler?(image)
            }
        }else {
            let image = info[(UIImagePickerController.InfoKey.originalImage)] as! UIImage?
            let asset = info[(UIImagePickerController.InfoKey.phAsset)] as? PHAsset
            if let image = image?.fixOrientation() {
                self.choseImageCompleteHandler?(image,asset)
            }
        }
        
        picker.dismiss(animated: true, completion: nil)
    }
}


// 相机和相册权限
extension BHImagePickManager {
    
    static func permissionForCamera(handler: @escaping (AVAuthorizationStatus) -> Void) {
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == .notDetermined {
            // 调用授权
            AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
                DispatchQueue.main.sync {
                    if granted == true {
                        handler(.authorized)
                    }else {
                        BHCommonTool.permisstionAlertShow(true)
                        handler(.denied)
                    }
                }
            })
        }else if authStatus == .authorized {
            handler(.authorized)
        } else {
            BHCommonTool.permisstionAlertShow(true)
            handler(.denied)
        }
    }
    
    static func permissionForAlbum(handler: @escaping (PHAuthorizationStatus) -> Void) {
        let authStatus = PHPhotoLibrary.authorizationStatus()
        if authStatus == .notDetermined {
            // 调用授权
            PHPhotoLibrary.requestAuthorization { (status:PHAuthorizationStatus) -> Void in
                DispatchQueue.main.sync {
                    if status == .authorized {
                        handler(.authorized)
                    }else {
                        handler(.denied)
                        BHCommonTool.permisstionAlertShow(false)
                    }
                }
            }
                
        }else if authStatus == .authorized {
            handler(.authorized)
        } else {
            handler(.denied)
            BHCommonTool.permisstionAlertShow(false)
        }
    }
}
